package cn.edu.uestc.cwdsj.utils;


import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;

import java.io.*;

/**
 * 提供读取配置文件的方法
 * Created by Eric on 2017/7/2.
 */
public class CfgUtil {
    private CfgUtil() {
    }

    public static Document getXMLDocument(String path) throws IOException, DocumentException {
        Logger logger = Logger.getLogger(CfgUtil.class.getClass());
        InputStream cfgFile = CfgUtil.class.getResourceAsStream(path);

        InputStreamReader reader;
        try {
            reader = new InputStreamReader(cfgFile, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.fatal("错误的字符集。");
            throw e;
        }
        BufferedReader bufferedReader = new BufferedReader(reader);

        StringBuilder builder = new StringBuilder();
        String tmp;
        try {
            for (tmp = bufferedReader.readLine(); tmp != null; tmp = bufferedReader.readLine()) {
                builder.append(tmp);
            }
        } catch (IOException e) {
            logger.fatal("无法读取异常列表。\n 路径 " + path + "\n 已读内容 \n" + builder.toString());
            throw e;
        }

        // update exList to String
        String cfgString = builder.toString();

        // parse and generate exMap
        Document cfgDocument;
        try {
            cfgDocument = DocumentHelper.parseText(cfgString);
        } catch (DocumentException e) {
            logger.fatal("无法解析异常列表文件。\n 路径 " + path + "\n 内容 \n" + cfgString);
            throw e;
        }
        return cfgDocument;
    }
}
